package com.gx.cn.hospitalmanage;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.gx.cn.hospitalmanage.MyFragmentOne.NetUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity  {


    private Button btnRegister,btnForgotPassword,mEmailSignInButton;

    private Intent intent;
    private TextView userID;
    private TextView userName;
    private TextView password;

    private  String result;
    Handler mHandler;

    String name,pwd,successfulles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //隐藏标题
        getSupportActionBar().hide();

        mHandler = new Handler();


        //进入主界面
        mEmailSignInButton = (Button) findViewById(R.id.btn_login);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText tvname=(EditText) findViewById(R.id.username); //获取用户名的控件
                  name= tvname.getText().toString();  //获取控件里面的值
                EditText tvPsd=(EditText) findViewById(R.id.password);
                 pwd=tvPsd.getText().toString();

                if(name==null || name.equals("")){
                    Toast.makeText (getApplicationContext(),"请输入用户名", Toast.LENGTH_LONG ).show();
                }else if(pwd==null || pwd.equals("")){
                    Toast.makeText (getApplicationContext(),"请输入密码", Toast.LENGTH_LONG ).show();
                }else {

                    new Thread() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            successfulles = init(name, pwd);
                            if (successfulles.equals("ok")) {
                                Intent it = new Intent(LoginActivity.this, MainActivity.class);
                                it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                startActivity(it);
                            } else {

                                Toast.makeText(getApplicationContext(), "用户或密码错误", Toast.LENGTH_LONG).show();
                            }
                            Looper.loop();
                        }

                    }.start();
                }
        //   requestClint();

            }
        });

         //注册
        btnRegister=(Button)findViewById(R.id.btnRegister);
        btnRegister.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it=new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(it);
            }
        });

      //忘记密码
        btnForgotPassword =(Button)findViewById(R.id.btnForgotPassword);
        btnForgotPassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it=new Intent(LoginActivity.this,AActivity.class);
                startActivity(it);
            }
        });


     }



     //json格式与服务端交互
     private String init(String name,String pwd){
    //     192.168.3.138 这个ip地址是Ipv4 地址 /20170112 是服务端的项目名称  /login/toJsonMain 是@RequestMapping的地址
    //      String urlPath="http://192.168.3.140:8080/20170112/logins/toJsonMain.action";
         String urlPath="http://192.168.43.43:8080/20170112/logins/toJsonMain.action";  // 这个是实体机的电脑 IP电脑 端口
         String successfull="ok";
         URL url;
         int id=0;
         try {
              url=new URL(urlPath);
             JSONObject jsonObject=new JSONObject();
             jsonObject.put("username",name);
             jsonObject.put("userpassword",pwd);

             //JSONObject Authorization =new JSONObject();
          //   Authorization.put("po类名",jsonObject 即po的字段)

             String content=String.valueOf(jsonObject);  //json串转string类型

             HttpURLConnection conn=(HttpURLConnection) url.openConnection(); //开启连接
             conn.setConnectTimeout(5000);

             conn.setDoOutput(true);
             conn.setRequestMethod("POST");
             conn.setRequestProperty("ser-Agent", "Fiddler");
             conn.setRequestProperty("Content-Type","application/json");
            //写输出流，将要转的参数写入流里
             OutputStream os=conn.getOutputStream();
             os.write(content.getBytes()); //字符串写进二进流
             os.close();

             int code=conn.getResponseCode();
             if(code==200){
                 //读取返回的json数据
                 InputStream inputStream=conn.getInputStream();
                 // 调用自己写的NetUtils() 将流转成string类型
                 successfull= NetUtils.readString(inputStream);

//                 Gson gson=new Gson();  //引用谷歌的json包
//                 User user=gson.fromJson(json,User.class); //谷歌的解析json的方法
//                 id =user.getUserid();  //然后user.get你想要的值
//                 String username=user.getUsername();
//                 String password=user.getUserpassword();


             }else{
                 Toast.makeText (getApplicationContext(),"数据提交失败", Toast.LENGTH_LONG ).show();
             }


         }catch (Exception e){

         }

         return  successfull;

     }



     //key/value格式与服务端交互
//     private  void requestClint(){
//
//        String url="http://192.168.42.207:8080/20170112/login/toMain.action";
//         AsyncHttpClient client=new AsyncHttpClient();
//         RequestParams params=new RequestParams();
//         params.put("username",name);
//         params.put("password",pwd);
//
//         client.post(url, params, new AsyncHttpResponseHandler() {
//             @Override
//             public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//
//                 String str=new String(responseBody);
//                 Gson gson=new Gson();
//                 User user=gson.fromJson(str,User.class);
//                 int id=user.getId();
//                 Toast.makeText(LoginActivity.this, "加载成功！", Toast.LENGTH_LONG).show();
//             }
//
//             @Override
//             public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//                 Toast.makeText(LoginActivity.this, "加载失败！", Toast.LENGTH_LONG).show();
//             }
//         });
//
//     }





}

